// @before-stub-for-debug-begin
#include <vector>
#include <string>
#include "commoncppproblem92.h"

using namespace std;
// @before-stub-for-debug-end

/*
 * @lc app=leetcode.cn id=92 lang=cpp
 *
 * [92] 反转链表 II
 *
 * https://leetcode-cn.com/problems/reverse-linked-list-ii/description/
 *
 * algorithms
 * Medium (55.17%)
 * Likes:    1195
 * Dislikes: 0
 * Total Accepted:    265.4K
 * Total Submissions: 481K
 * Testcase Example:  '[1,2,3,4,5]\n2\n4'
 *
 * 给你单链表的头指针 head 和两个整数 left 和 right ，其中 left  。请你反转从位置 left 到位置 right 的链表节点，返回
 * 反转后的链表 。
 *
 *
 * 示例 1：
 *
 *
 * 输入：head = [1,2,3,4,5], left = 2, right = 4
 * 输出：[1,4,3,2,5]
 *
 *
 * 示例 2：
 *
 *
 * 输入：head = [5], left = 1, right = 1
 * 输出：[5]
 *
 *
 *
 *
 * 提示：
 *
 *
 * 链表中节点数目为 n
 * 1
 * -500
 * 1
 *
 *
 *
 *
 * 进阶： 你可以使用一趟扫描完成反转吗？
 *
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */

class Solution
{
public:
    ListNode *reverseBetween(ListNode *head, int left, int right)
    {
        ListNode *ptr = new ListNode(-1, head);
        ListNode *pre = nullptr;
        ListNode *temp = new ListNode;
        ListNode *l1_tail = new ListNode;
        ListNode *l2_tail = new ListNode;
        int cnt = 1;
        int flag = 0;
        int isinl1=0;
        while (head != nullptr)
        {
            if (cnt < left)
            {
                if(isinl1==0){
                    isinl1=1;
                }
                l1_tail = head;
                head = head->next;
                cnt++;
            }
            else if (cnt >= left && cnt <= right)
            {
                while (cnt >= left && cnt <= right)
                {
                    temp = head->next;
                    head->next = pre;
                    pre = head;
                    if (flag == 0)
                    {
                        l2_tail = pre;
                        flag = 1;
                    }
                    head = temp;
                    cnt++;
                }
                if(l1_tail){
                l1_tail->next = pre;}
                if(isinl1==0){
                    ptr=l1_tail;
                }
            }
            else
            {
                l2_tail->next = head;
                l2_tail = head;
                head = head->next;
                cnt++;
            }
        }
        return ptr->next;
    }
};

// @lc code=end
